<script setup lang="ts">
import { Dialog, Form, Field, CellGroup, Checkbox, showNotify } from "vant";
import { reactive } from "vue";
import axios from "axios";
import { useConfigStore } from "@/stores/models/config";

const configStore = useConfigStore();

const dialogData = reactive({
    visible: false,
    loading: false,
    showCancelButton: false
});

const handleShow = (cancelBtn?: boolean): void => {
    dialogData.showCancelButton = cancelBtn ?? false;
    dialogData.visible = true;
};

const formData = reactive({
    ip: "",
    remember: true
});

const hanldeConnectDevice = async (action: string): Promise<boolean> => {
    if (action !== "confirm") return true;
    try {
        dialogData.loading = true;
        const response = await axios.get(`http://${formData.ip}/system/info`);
        configStore.updateDeviceConfig(response.data);
        configStore.$patch({
            device_ip: formData.ip
        });
        showNotify({
            type: "success",
            message: "连接成功"
        });
        return true;
    } catch (error) {
        showNotify({
            type: "danger",
            message: "连接失败"
        });
        return false;
    } finally {
        dialogData.loading = false;
    }
};

defineExpose({
    show: handleShow
});
</script>
<template>
    <Dialog
        v-model:show="dialogData.visible"
        title="连接设备"
        :show-cancel-button="dialogData.showCancelButton"
        confirm-button-text="连接"
        :before-close="hanldeConnectDevice"
        :cancel-button-disabled="dialogData.loading"
    >
        <Form class="my-4" :disabled="dialogData.loading">
            <CellGroup inset>
                <Field
                    autofocus
                    required
                    label="IP地址"
                    label-align="top"
                    placeholder="请输入设备局域网IP地址"
                    v-model="formData.ip"
                />
                <Field name="checkbox">
                    <template #input>
                        <Checkbox v-model="formData.remember" shape="square" disabled>
                            保存连接
                        </Checkbox>
                    </template>
                </Field>
            </CellGroup>
        </Form>
    </Dialog>
</template>
